package com.thinkit.bigdata.web.service.impl.perCenter;

import com.google.common.base.Strings;
import com.thinkit.bigdata.core.ConfigHelper;
import com.thinkit.bigdata.core.util.TaskUtil;
import com.thinkit.bigdata.core.util.es.ESUtil;
import com.thinkit.bigdata.web.controller.pubmet.PubMethod;
import com.thinkit.bigdata.web.coremet.SystemStatic;
import com.thinkit.bigdata.web.model.es.countEs.CountSource;
import com.thinkit.bigdata.web.model.result.HtmlResult;
import com.thinkit.bigdata.web.service.perCenter.MyAssService;
import org.apache.log4j.Logger;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * Created by hccl on 2018/9/10.
 */
@Service
public class MyAssServiceImpl implements MyAssService {

    private static Logger logger = Logger.getLogger(MyAssServiceImpl.class);

    @Resource
    private ESUtil esUtil;

    public BoolQueryBuilder getQuery(String logTxt, HttpServletRequest request) {
        String workId = request.getParameter("workId");//质检任务名称
        String monthlyAssess = request.getParameter("monthlyAssess");//质检考核周期 开始时间
        String callStartTime = request.getParameter("callStartTime");//质检考核周期 开始时间
        String callEndTime = request.getParameter("callEndTime");//质检考核周期 结束时间
        String seatGroup = request.getParameter("seatGroup");//坐席班组
        String seatId = request.getParameter("seatId");//坐席工号
        String seatName = request.getParameter("seatName");//坐席工号
        String province = request.getParameter("callerloc");//省份
        String workScoreMin = request.getParameter("workScoreMin");//得分范围
        String workScoreMax = request.getParameter("workScoreMax");//得分范围
        String sendType = request.getParameter("sendType");//请求类型
        logger.info(logTxt + "workId = " + workId);
        logger.info(logTxt + "seatGroup = " + seatGroup);
        logger.info(logTxt + "seatId = " + seatId);
        logger.info(logTxt + "seatName = " + seatName);
        logger.info(logTxt + "callerloc = " + province);
        logger.info(logTxt + "callStartTime = " + callStartTime);
        logger.info(logTxt + "callEndTime = " + callEndTime);
        logger.info(logTxt + "workScoreMin = " + workScoreMin);
        logger.info(logTxt + "workScoreMax = " + workScoreMax);
        logger.info(logTxt + "sendType = " + sendType);

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //数据权限
        if (Strings.isNullOrEmpty(sendType)) {//质检结果页面
            esUtil.formatQResult(boolQuery, seatId);
        }
        if (!Strings.isNullOrEmpty(seatName)) {
            boolQuery.must(QueryBuilders.matchQuery("seatName", seatName));
        }
        if (!Strings.isNullOrEmpty(seatGroup)) {
            boolQuery.must(QueryBuilders.matchQuery("groupId", seatGroup));
        }
        if (!Strings.isNullOrEmpty(province)) {
            boolQuery.must(QueryBuilders.matchQuery("province", province));
        }
        if (!Strings.isNullOrEmpty(monthlyAssess)) {
            boolQuery.must(QueryBuilders.matchQuery("monthlyAssess", monthlyAssess));
        }
        if (!Strings.isNullOrEmpty(callStartTime)) {
            boolQuery.must(QueryBuilders.rangeQuery("monthlyAssess").gte(callStartTime));
        }
//        else {
//            boolQuery.must(QueryBuilders.rangeQuery("monthlyAssess").gte(201801));
//        }
        if (!Strings.isNullOrEmpty(callEndTime)) {
            boolQuery.must(QueryBuilders.rangeQuery("monthlyAssess").lte(callEndTime));
        }
        if (!Strings.isNullOrEmpty(workId)) {
            boolQuery.must(QueryBuilders.matchQuery("workId", workId));
        }
        if (!Strings.isNullOrEmpty(workScoreMin)) {
            boolQuery.must(QueryBuilders.rangeQuery("workScore").gte(workScoreMin));
        }
        if (!Strings.isNullOrEmpty(workScoreMax)) {
            boolQuery.must(QueryBuilders.rangeQuery("workScore").lte(workScoreMax));
        }
        return boolQuery;
    }

    @Override
    public HtmlResult getDataList(HttpServletRequest request) {
        String pageNum = request.getParameter("pageNum");//起始页
        String pageSize = request.getParameter("pageSize");//每页条数
        String sortName = request.getParameter("sortName");//录音流水
        String sortOrder = request.getParameter("sortOrder");//录音流水
        BoolQueryBuilder boolQuery = getQuery("【获取我的考核信息列表】", request);
        if (!SystemStatic.crud.indexExists(SystemStatic.COUNT_ES_INDEX)) {
            return HtmlResult.success("暂无数据");
        }
        String[] includes = new String[]
                {
                        "id",
                        "province",
                        "workId",
                        "workName",
                        "monthlyAssess",
                        "cycleAssess",
                        "assStartDate",
                        "assEndDate",
                        "groupId",
                        "groupName",
                        "seatId",
                        "seatName",
                        "workScore",
                        "audioSum",
                        "inputTime",
                        "modelRules.updateTime"
                };
        List<String> docList = SystemStatic.crud.queryMyAssess(
                SystemStatic.COUNT_ES_INDEX,
                SystemStatic.COUNT_ES_TYPE,
                Integer.parseInt(pageNum),
                Integer.parseInt(pageSize),
                boolQuery,
                SystemStatic.crud.formatCloumn(sortName, SystemStatic.COUNT_ES_INDEX),
                sortOrder,
                includes
        );
        logger.info("获取数据条数为：" + docList.size());
        return HtmlResult.success(
                esUtil.strs2Entitys1(docList),
                SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.COUNT_ES_INDEX, SystemStatic.COUNT_ES_TYPE, boolQuery)
        );
    }

    public HtmlResult getDataList(String code) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        esUtil.formatQResult(boolQuery, null);
        if (!SystemStatic.crud.indexExists(SystemStatic.COUNT_ES_INDEX)) {
            return HtmlResult.success("暂无数据");
        }
        List<CountSource> countSources = new ArrayList<>();
        //总条数
        Integer sum = SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.COUNT_ES_INDEX, SystemStatic.COUNT_ES_TYPE, boolQuery);
        //单词查询条数
        int excleMax = ConfigHelper.getInt("export.data.sheet.max.number", 1000);
        List<Integer> pageTout = TaskUtil.formatSum(sum, excleMax);//todo最后一个数字需要特殊处理:6022
        String[] includes = new String[]
                {
                        "province",
                        "workId",
                        "workName"
                };
        for (Integer aPageTout : pageTout) {
            List<String> docList = SystemStatic.crud.queryMyAssess(
                    SystemStatic.COUNT_ES_INDEX,
                    SystemStatic.COUNT_ES_TYPE,
                    aPageTout,
                    excleMax,
                    boolQuery,
                    "inputTime",
                    "desc",
                    includes
            );
            if (docList.isEmpty()) continue;
            countSources.addAll(esUtil.strs2Entitys1(docList));
        }
        logger.info("获取数据条数为：" + countSources.size());
        List<Map<String, String>> mapList = new ArrayList<>();
        List<Long> workIds = new ArrayList<>();
        for (CountSource source : countSources) {
            if (!Strings.isNullOrEmpty(code) && !code.equals(source.getProvince())) {
                continue;
            }
            if (workIds.contains(source.getWorkId())) {
                continue;
            }
            workIds.add(source.getWorkId());
            Map<String, String> map = new HashMap<>();
            map.put("workId", source.getWorkId().toString());
            map.put("workName", source.getWorkName());
            mapList.add(map);
        }
        return HtmlResult.success(mapList);
    }

    @Override
    public HtmlResult getDataListById(HttpServletRequest request) {
        String serialNumber = request.getParameter("id");
        CountSource source = getSourceBySerialNumber(serialNumber);
        return HtmlResult.success(source.getModelRules());
    }

    @Override
    public HtmlResult getDataListByMes(HttpServletRequest request) {
        String workId = request.getParameter("workId");//质检任务名称
        String callStartTime = request.getParameter("callStartTime");//质检考核周期 开始时间
        String callEndTime = request.getParameter("callEndTime");//质检考核周期 结束时间
        String seatId = request.getParameter("seatId");//坐席工号
        String seatName = request.getParameter("seatName");//坐席工号
        String ruleId = request.getParameter("ruleId");//规则ids
        String pageNum = request.getParameter("pageNum");//起始页
        String pageSize = request.getParameter("pageSize");//每页条数
        String sortName = request.getParameter("sortName");//录音流水
        String sortOrder = request.getParameter("sortOrder");//录音流水
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (!Strings.isNullOrEmpty(seatId)) {
            boolQuery.must(QueryBuilders.matchQuery("voiceInfo.seatId", seatId));
        }
        if (!Strings.isNullOrEmpty(seatName)) {
            boolQuery.must(QueryBuilders.matchQuery("voiceInfo.seatName", seatName));
        }
        PubMethod.formatTime(boolQuery, callStartTime, callEndTime);
        boolQuery.must(
                QueryBuilders.nestedQuery(
                        "workScores",
                        QueryBuilders.boolQuery()
                                .must(QueryBuilders.matchQuery("workScores.workId", workId))
                                .must(
                                        QueryBuilders.nestedQuery(
                                                "workScores.modelRules",
                                                QueryBuilders.matchQuery("workScores.modelRules.ruleId", ruleId),
                                                ScoreMode.None

                                        )
                                ),
                        ScoreMode.None
                )
        );
        String[] includes = new String[]
                {
                        "serialNumber",
                        "voiceInfo",
                        "workScores"
                };
        List<String> docList = SystemStatic.crud.queryMapQBuilderRetRuleAndWork(
                SystemStatic.AUDIO_ES_INDEX,
                SystemStatic.AUDIO_ES_TYPE,
                Integer.parseInt(pageNum),
                Integer.parseInt(pageSize),
                boolQuery,
                SystemStatic.crud.formatCloumn(sortName, SystemStatic.AUDIO_ES_INDEX),
                sortOrder,
                includes
        );
        logger.info("获取数据条数为：" + docList.size());
        return HtmlResult.success(
                esUtil.formatModel(docList, workId),
                SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, boolQuery)
        );
    }

    private CountSource getSourceBySerialNumber(String serialNumber) {
        String mgs = SystemStatic.crud.get(SystemStatic.COUNT_ES_INDEX, SystemStatic.COUNT_ES_TYPE, serialNumber);
        return esUtil.str2entity1(mgs);
    }
}
